package com.rongzhe.house.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.rongzhe.house.R;
import com.rongzhe.house.manager.UserManager;
import com.rongzhe.house.presenter.BasePresenter;
import com.rongzhe.house.ui.UiControlInterface;
import com.rongzhe.house.utils.UIUtils;

import java.util.ArrayList;

/**
 * Created by huang on 2017/8/8.
 */

public abstract  class BaseActivity<T extends BasePresenter> extends AppCompatActivity
        implements UiControlInterface {
    protected final String TAG = getClass().getSimpleName();
    private static final int REQUEST_PERMISSION = 1;
    private Dialog mDialog;
    private Dialog mProgressDialog;
    protected T mPresenter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = createPresenter();
        if (mPresenter != null) {
            mPresenter.onCreate();
        }
        configActionBar();
        if(needRequestPermission() != null) {
            checkForPermission(needRequestPermission());
        }
    }

    protected String[] needRequestPermission() {
        return null;
    }

    protected void onRequestPermissGranted(boolean granted, String permission) {
    }

    public void checkForPermission(String[] permissionsToCheck) {
        if(permissionsToCheck == null || permissionsToCheck.length < 1) {
            return;
        }
        ArrayList<String> permissionToCheck = new ArrayList<>();
        for (String permission : permissionsToCheck) {
            if (ActivityCompat.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                //If permission do not granted, get the permission.
                permissionToCheck.add(permission);
            } else {
                //If the permission is granted, just callback to do something.
                onRequestPermissGranted(true, permission);
            }
        }
        if (permissionToCheck.size() > 0) {
            String[] permissionArray = new String[permissionToCheck.size()];
            permissionToCheck.toArray(permissionArray);
            requestForPermission(permissionArray);
        }
    }

    private void requestForPermission(final String [] permissions) {
        boolean needExplain = false;
        for(String permission : permissions) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                needExplain = true;
            }
        }
        if (needExplain) {
            //需要向客户解释为什么需要Location 权限
            showAlert(UIUtils.createTwoButtonDialog(this, getString(R.string.hint),
                    getString(R.string.need_auth_hint), getString(android.R.string.cancel),
                    getString(android.R.string.ok), null, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ActivityCompat.requestPermissions(BaseActivity.this,
                                    permissions, REQUEST_PERMISSION);
                        }
                    }));
        } else {
            // Camera permission has not been granted yet. Request it directly.
            ActivityCompat.requestPermissions(this,
                    permissions, REQUEST_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSION) {
            for (int i = 0; i< grantResults.length; i++) {
                if(grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    onRequestPermissGranted(true, permissions[i]);
                } else {
                    onRequestPermissGranted(false, permissions[i]);
                }
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mPresenter != null) {
            mPresenter.start(getIntent());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mPresenter != null) {
            mPresenter.stop();
        }
    }

    protected abstract T createPresenter();

    protected void configActionBar() {
        if(null == getSupportActionBar()){
            return;
        }
        if (!showActionBar()) {
            getSupportActionBar().hide();
        } else {
            getSupportActionBar().show();
            configActionBar(getActionTitle());
        }
        doSomthingAfterConfigBar(getSupportActionBar());
    }

    protected void doSomthingAfterConfigBar(ActionBar actionBar) {
        //do nothing
    }

    //配置action bar
    private void configActionBar(String title) {
        getSupportActionBar().setCustomView(R.layout.action_title_layout);
        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        //去除actionbar兩邊的padding
        Toolbar parent = (Toolbar) getSupportActionBar().getCustomView().getParent();
        parent.setContentInsetsAbsolute(0, 0);
        //以下代码用于去除阴影
        if(Build.VERSION.SDK_INT>=21){
            getSupportActionBar().setElevation(0);
        }
        View actionbarLayout = getSupportActionBar().getCustomView();
        if (getActionBarBackground() != -1) {
            actionbarLayout.setBackgroundColor(getActionBarBackground());
        }
        View leftActionItem = actionbarLayout.findViewById(R.id.left_button);
        if (hideLeftActionItem()) {
            leftActionItem.setVisibility(View.GONE);
        } else if (getLeftActionClickAction() != null) {
            leftActionItem.setOnClickListener(getLeftActionClickAction());
        } else {
            leftActionItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
        ((TextView) actionbarLayout.findViewById(R.id.action_text)).setText(title);
        TextView rightView = (TextView) actionbarLayout.findViewById(R.id.text_right_button);
        if (TextUtils.isEmpty(getRightActionText())) {
            rightView.setVisibility(View.GONE);
        } else {
            rightView.setText(getRightActionText());
            rightView.setVisibility(View.VISIBLE);
        }
        if (getRightActionClickAction() != null) {
            rightView.setOnClickListener(getRightActionClickAction());
        }
    }

    /**
     * 子类通过重载这个方法控制是否隐藏左边按钮
     * @return false不隐藏  true 隐藏
     */
    protected boolean hideLeftActionItem() {
        return false;
    }

    /**
     *
     * 子类通过重载这个方法控制actionbar上左边按键的按键事件
     * @return actionbar左边按键的按键监听, 返回null将会使用默认监听
     */
    protected View.OnClickListener getLeftActionClickAction() {
        return null;
    }

    /**
     * 配置actionbar的默认颜色
     * @return -1不改变使用默认颜色.
     */
    protected int getActionBarBackground() {
        return -1;
    }

    /**
     * 子类通过重载这个方法控制actionbar右边按键的图标显示
     * @return -1不显示右键, 其他值为右键的图标
     */
    protected String getRightActionText() {
        return null;
    }

    /**
     * 子类通过重载这个方法控制actionbar上右边按键的按键事件
     * @return actionbar右边按键的按键监听
     */
    protected View.OnClickListener getRightActionClickAction() {
        return null;
    }

    /**
     * 子类通过重载这个方法显示actionbar上的title
     * @return title
     */
    protected String getActionTitle() {
        return null;
    }

    protected boolean showActionBar() {
        return true;
    }

    @Override
    public Context getContextInternal() {
        return this;
    }

    @Override
    public void launchActivityForResult(int requestCode, Intent intent) {
        startActivityForResult(intent, requestCode);
    }

    @Override
    public boolean handleNoLogin() {
        if(!UserManager.getInstance().isLogin()) {
            Intent loginIntent = new Intent(this, LoginActivity.class);
            startActivity(loginIntent);
            return true;
        }
        return false;
    }

    @Override
    public void launchActivity(boolean loginRequire, Intent intent) {
        if (loginRequire && handleNoLogin()) {
            return;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    @Override
    public void showAlert(Dialog dialog) {
        dismissAlert();
        mDialog = dialog;
        dialog.show();
    }

    @Override
    public void dismissAlert() {
        if (mDialog != null) {
            if (mDialog.isShowing()) {
                mDialog.dismiss();
            }
            mDialog = null;
        }
    }

    @Override
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showProgress(String message) {
        dismissProgress();

        LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.progress_dialog_custom, null);// 得到加载view
        // main.xml中的ImageView
        ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(
                this, R.anim.loading_animation);
        // 使用ImageView显示动画
        spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        tipTextView.setText(message);// 设置加载信息

        mProgressDialog= new Dialog(this, R.style.progressDialog);// 创建自定义样式dialog
        mProgressDialog.setCancelable(false);// 不可以用“返回键”取消
        mProgressDialog.setContentView(v, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局

        TextPaint textPaint = tipTextView.getPaint();
        float sizePx = textPaint.measureText(message);
        setDialogLayoutParams((int) sizePx, mProgressDialog);
        mProgressDialog.show();
    }

    private void setDialogLayoutParams(int contentWidth, Dialog dialog) {
        Window dialogWindow = dialog.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager m = getWindowManager();
        m.getDefaultDisplay().getMetrics(dm);
        int maxWidth = (int) (dm.widthPixels * 0.85F);
        int minWidth = (int) (dm.widthPixels * 0.45F);
        if (contentWidth < minWidth) {
            contentWidth = minWidth;
        }
        if (contentWidth > maxWidth) {
            contentWidth = maxWidth;
        }
        lp.width = contentWidth;
        dialogWindow.setAttributes(lp);
    }

    @Override
    public void dismissProgress() {
        if (mProgressDialog != null) {
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            mProgressDialog = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mPresenter != null) {
            if (mPresenter.handleActivityResult(requestCode, resultCode, data)) {
                return;
            }
        }
    }
}
